<script setup>
import { reactive, ref } from "vue";
import { checkPhoneNumber } from "@/utils/checkPhoneNumber"
import { ElMessage } from 'element-plus'
import { getCodeClick } from '@/utils/getCode'
import eventBus from '@/utils/eventBus.js'
const phoneForm = reactive({
  phone: '',  // 手机号
  code: ''    // 验证码
})
const rules = reactive({
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

// 获取手机号
const isDisabledBtn = ref(true); // 是否禁用按钮
const isPhoneNumber = ref(false); // 是否获取正确的手机号
const getPhoneNumber = () => {
  const result = checkPhoneNumber(phoneForm.phone);
  isPhoneNumber.value = result;
  isDisabledBtn.value = !result;
}

// 获取验证码
const codeRef = ref(null);
// const codeNumber = ref(); // 保存验证码
const getCode = async() => {
  ElMessage({
    message: `验证码已发送至【${phoneForm.phone}】，\n请注意查收！`,
    showClose: true,
    center: true
  })
  // 当点击获取验证码按钮时，变为禁用状态
  isDisabledBtn.value = true;
  getCodeClick(codeRef).then(res => {
    if (res) {
      codeRef.value.$el.textContent = res;
      isDisabledBtn.value = false
    }
  })
}

// 表单提交校验 
const formRef = ref();
eventBus.on('phoneLogin',submitForm)
function submitForm(){
  formRef.value?.validate(vaild => {
    if (vaild && isPhoneNumber.value) {
      console.log('表单校验成功！')
    }
  })
}
</script>

<template>
    <!-- 手机号登录 -->
  <div class="phone_login">
    <el-form
        :model="phoneForm"
        :rules="rules"
        ref="formRef"
        class="formEl"
    >
        <el-form-item label="手机号" prop="phone" class="phone">
            <el-input 
              v-model="phoneForm.phone" 
              placeholder="请输入手机号" 
              @input="getPhoneNumber"
            />
            <div class="tip" v-if="phoneForm.phone">
              <span class="success" v-if="isPhoneNumber">手机号格式正确！</span>
              <span class="error" v-else>手机号格式不正确！</span>
            </div>
        </el-form-item>
        <el-form-item label="验证码" prop="code" class="code">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-input
                  v-model="phoneForm.code"
                  placeholder="验证码"
                />
              </el-col>
              <el-col :span="8">
                <el-button 
                  type="primary"
                  @click="getCode" 
                  ref="codeRef"
                  :disabled="isDisabledBtn"
                >
                   获取验证码
                </el-button>
              </el-col>
            </el-row>
        </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
.phone_login {
  .phone {
    .tip {
      height: 20px;
      line-height: 20px;
      font-size: 12px;
    }
  }
}
.success {
  color: #67C23A
}
.error {
  color: #F56C6C;
}
</style>